<?php

namespace App\Http\Controllers\home;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;
use Hash;
use Mail;
class RegisterController extends Controller
{
    /**
     * getIndex() 前台注册首页
     *
     * @return 返回前台注册首页视图
     */
    public function getIndex(){

        return view('home.register.index');
    }


    /**
     * postEmail() ajax验证邮箱是否被占用
     * 
     * 
     */
    public function postEmail(Request $request){
    	// 邮箱验证
    	$email = $request -> input('user_email');
    	if(DB::table('users')->where('user_email',$email)->first()){
    		echo 2;
    	}else{
    		echo 1;
    	}
    }

    /**
     * postInsert() 邮箱注册方法
     *
     * @param $s    array       接收需要验证的值
     * @param $reg  string      接收需要验证的值
     * @param $id   int         插入数据的id
     * @return        返回邮箱验证成功过显示的视图
     */
    public function postInsert(Request $request){
  	
    	// 验证验证码是否一致
    	if(session('code') != $request -> input('code')){  		
    		return back() -> withInput() -> with('error','验证码错误');    		
    	}
    	// 验证密码是否一致
    	$s = $request -> only(['user_email','user_pass','repassword']);
    	if($s['user_pass'] != $s['repassword']){
    		return back() -> withInput() -> with('error','2次密码不一致'); 
    	}
    	// 验证密码长度
    	$reg = "/^\S{6,18}$/i";
    	if(!preg_match($reg,$s['user_pass'])){
    		return back() -> withInput() -> with('error','密码长度不符要求');
    	}	
    	// 组装数据-----哈希加密
    	$arr['user_pass'] = Hash::make($s['user_pass']);
    	$arr['user_createtime'] = date('Y-m-d H:i:s',time());
    	$arr['user_ip'] = $request->getClientIp();
    	$arr['user_email'] = $s['user_email'];
    	$arr['user_token'] = str_random(50);   	
    	// 检验帐号的重复性
    	if(DB::table('users')->where('user_email',$s['user_email'])->first()){
    		return back() -> withInput() -> with('error','此邮箱已经注册');
    	}
    	// 插入数据
    	$id = DB::table('users') -> insertGetId($arr);
    	if($id > 0){
    		// 发送的邮箱$arr['user_email'] 发送的$id token值$arr['user_token']
    		self::mailto($arr['user_email'],$id,$arr['user_token']);
    		return view('home.email.success') -> with('email',$arr['user_email']);
    	}

    }

	/**
     * mailto() 发送邮箱验证方法
     * 
     * @param   $email      string  用户邮箱
     * @param   $id         int     用户id
     * @param   $user_token string  用户user_token值
     */   
    static public function mailto($email,$id,$user_token){
    	Mail::send('home.email.index', ['id' => $id,'user_token' => $user_token], function ($m) use ($email) {
            $m->to($email)->subject('数码宝贝注册邮件!!');
        });
    }
    /**
     * getJihuo() 激活邮箱的方法
     * 
     * @param   $s     array  接收传递过来的参数
     * @param   $arr   array  设置用户的状态及token值
     * @param   $res   bool   返回修改后布尔值
     * @return  返回到前台登录界面
     */
    public function getJihuo(Request $request){
    	$s = $request -> only(['id','user_token']);
    	// var_dump($s);
    	$arr['user_status'] = 2;
    	$arr['user_token'] = str_random(50);
    	// 修改权限
    	$res = DB::table('users') ->where('id',$s['id']) ->where('user_token',$s['user_token']) -> update($arr);
    	// 查找id下的邮箱
    	$dd = DB::table('users') -> where('id',$s['id']) ->first();
    	// var_dump($res);
    	if($res){
    		return view('/home/login/index',['user_phone'=>$dd['user_email'],'success'=>'恭喜:注册成功请登录']);
    	}else{
    		return back() -> withInput() -> with('error','抱歉:注册失败');
    	}
    }

    /**
     * postPhonetest() ajax验证手机号码
     * 
     * @param   
     * @param   
     * @param   
     */ 
    public function postPhonetest(Request $request){
    	$user_phone = $request -> input('user_phone');
    	if(DB::table('users')->where('user_phone',$user_phone)->first()){
    		echo 1;
    	}else{
    		echo 2;
    	}
    }

    /**
     * xml_to_array() xml转为数组
     * 
     * @param   
     * @param   
     * @param   
     */ 
	static function xml_to_array($xml){
		$reg = "/<(\w+)[^>]*>([\\x00-\\xFF]*)<\\/\\1>/";
		if(preg_match_all($reg, $xml, $matches)){
			$count = count($matches[0]);
			for($i = 0; $i < $count; $i++){
			$subxml= $matches[2][$i];
			$key = $matches[1][$i];
				if(preg_match( $reg, $subxml )){
					$arr[$key] = self::xml_to_array( $subxml );
				}else{
					$arr[$key] = $subxml;
				}
			}
		}
		return $arr;
	}

    /**
     * post() 请求数据到短信接口，检查环境是否 开启 curl_init。
     * 
     * @param   
     * @param   
     * @param   
     */ 
	static function Post($curlPost,$url){
			$curl = curl_init();
			curl_setopt($curl, CURLOPT_URL, $url);
			curl_setopt($curl, CURLOPT_HEADER, false);
			curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($curl, CURLOPT_NOBODY, true);
			curl_setopt($curl, CURLOPT_POST, true);
			curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
			$return_str = curl_exec($curl);
			curl_close($curl);
			return $return_str;
	}

    /**
     * phone() 获取手机验证码
     * 
     * @param $target       string 短信接口地址  
     * @param $post_data    string 设置APIID APIKEY 
     * @param $mobile_code  int    生成手机验证码 
     */ 
    static public function postPhone(){
    	//短信接口地址
		$target = "http://106.ihuyi.cn/webservice/sms.php?method=Submit";
		//获取手机号
		$mobile = $_POST['mobile'];
		//生成的随机数
		session(['phone_code'=>rand(100000,999999)]);
		$mobile_code = session('phone_code');
		if(empty($mobile)){
			exit('手机号码不能为空');
		}
		// //防用户恶意请求
		// if(empty($_SESSION['send_code']) or $send_code!=$_SESSION['send_code']){
		// 	exit('请求超时，请刷新页面后重试');
		// }

		$post_data = "account=C68532478&password=b562d07e58803b52bd2a6d05e474b8e9&mobile=".$mobile."&content=".rawurlencode("您的验证码是：".$mobile_code."。请不要把验证码泄露给其他人。");
		//用户名请登录用户中心->验证码、通知短信->帐户及签名设置->APIID
		//查看密码请登录用户中心->验证码、通知短信->帐户及签名设置->APIKEY
		$gets =  self::xml_to_array(self::Post($post_data, $target));
		if($gets['SubmitResult']['code']==2){

		}
		  echo $gets['SubmitResult']['msg'];
	}
	/**
     * postInsert2() 手机提交注册
     * 
     * @param $data         array      接收  
     * @param $reg          string     密码正则 
     * @param $user_phone   string     手机号码 
     */
	public function postInsert2(Request $request){
		$data = $request->all();
		if(session('phone_code') != $data['phone_code']){
		return back() -> withInput() -> with('error','短信验证码错误'); 
		}
		// 验证验证码是否一致
    	if(session('code') != $request -> input('code')){  		
		return back() -> withInput() -> with('error','验证码错误');    		
		}
    	// 验证密码是否一致
    	if($data['user_pass'] != $data['repassword']){
    		return back()-> with('error','2次密码不一致'); 
    	}
    	// 验证密码长度
    	$reg = "/^\S{6,18}$/i";
    	if(!preg_match($reg,$data['user_pass'])){
    		return back() -> with('error','密码长度不符要求');
    	}
    	// 组装数据-----哈希加密
    	$arr['user_pass'] = Hash::make($data['user_pass']);
    	$arr['user_createtime'] = date('Y-m-d H:i:s',time());
    	$arr['user_ip'] = $request->getClientIp();
    	$arr['user_phone'] = $data['user_phone'];
    	$arr['user_token'] = str_random(50);
    	$arr['user_status'] = 2;   	
    	// var_dump($arr);
    	// 检验帐号的重复性
    	if(DB::table('users')->where('user_phone',$data['user_phone'])->first()){
    		return back() -> withInput() -> with('error','抱歉:该手机号已经注册');
    	}
    	// 插入数据
    	$id = DB::table('users') -> insertGetId($arr);
    	$user_phone = $arr['user_phone'];
    	if($id > 0){
    		return view('/home/login/index',['user_phone'=>$user_phone,'success'=>'恭喜:注册成功请登录']);
    		 // ,['user_phone'=> $arr['user_phone']]
    	}else{
    		return back() -> withInput() -> with('error','抱歉:注册失败');
    	}
	}

    /**
     * postRepassword() 通过手机找回密码的方法
     * 
     * @param 
     * @param 
     * @return      返回找回密码页面视图
     */
    public function getRepassword(){
        return view('/home/password/index');
    }

    public function postPass(Request $request){
        $data = $request->all();
        if(session('phone_code') != $data['phone_code']){
            return back() -> withInput() -> with('error','短信验证码错误'); 
        }
        $user_phone = $data['user_phone'];
        $arr['user_pass'] = Hash::make($data['user_pass']);
        $res = DB::table('users') -> where('user_phone',$user_phone) -> update($arr);
        if($res){
            
            return view('/home/login/index',['user_phone'=>$user_phone,'success'=>'恭喜:密码修改成功请登录']);
             // ,['user_phone'=> $arr['user_phone']]
        }else{
            return back() -> withInput() -> with('error','抱歉:密码修改失败');
        }

    }
}
